package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.common.Constant;
import com.engineering.elink.dao.CompanyRecordMapper;
import com.engineering.elink.dao.UserMapper;
import com.engineering.elink.domain.CompanyRecord;
import com.engineering.elink.service.CompanyRecordService;

@Service
public class CompanyRecordServiceImpl implements CompanyRecordService {

	@Autowired
	private CompanyRecordMapper companyRecordMapper;

	@Autowired
	private UserMapper userMapper;

	@Override
	public boolean addCompanyRecord(String fromUserId, String toUserId) {
		Map<String, Object> fromUserMap = userMapper.selectByUserId(fromUserId);
		Map<String, Object> toUserMap = userMapper.selectByUserId(toUserId);
		if (!fromUserId.equals(toUserId)
				&& fromUserMap != null
				&& toUserMap != null
				&& (int) fromUserMap.get("userType") == Constant.companyUserType
				&& (int) toUserMap.get("userType") == Constant.companyUserType) {
			CompanyRecord companyRecord = companyRecordMapper
					.selectByFromAndTo(fromUserId, toUserId);
			if (companyRecord == null) {
				companyRecord = new CompanyRecord();
				companyRecord.setCreateTime(new Date());
				companyRecord.setFromUserId(fromUserId);
				companyRecord.setToUserId(toUserId);
				companyRecord.setBrowseCount(1);
				companyRecordMapper.insertSelective(companyRecord);
			} else {
				companyRecord
						.setBrowseCount(companyRecord.getBrowseCount() + 1);
				companyRecordMapper.updateByPrimaryKeySelective(companyRecord);
			}
			return true;
		}
		return false;
	}

	@Override
	public List<Map<String, Object>> getCompanyRecordList(String toUserId) {
		Map<String, Object> toUserMap = userMapper.selectByUserId(toUserId);
		if (toUserMap != null && (int)toUserMap.get("userType") == Constant.companyUserType) {
			return companyRecordMapper.selectCompanyRecordList(toUserId);
		}
		return null;
	}

}
